package com.hz.urlcert.tls;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;


public class HttpClient {
    private static final String a = HttpClient.class.getSimpleName();

    private URL b;

    private Map<String, String> c;

    private Map<String, List<String>> d;

    private SSLSocketFactory mSSLSocketFactory;
    private HttpMethod f;
    private String g;
    private String h = "";
    private int i;
    private boolean j = true;
    private MyHostnameVerifier mHostnameVerifier;
    private SSLContext mSslContext;

    public enum HttpMethod {
        GET,
        POST,
        DELETE;
    }

    public HttpClient(String paramString, HttpMethod paramHttpMethod) throws MalformedURLException {
        this.b = new URL(paramString);
        this.f = paramHttpMethod;
    }

    public HttpClient setAllowedSSLProtocols(String[] paramArrayOfString) {
        if (paramArrayOfString != null) {
            this.mSSLSocketFactory = new TlsSocketFactory(paramArrayOfString);
        }
        return this;
    }

    public HttpClient addHeader(String paramString1, String paramString2) {
        if (this.c == null) {
            this.c = new HashMap<>();
        }
        this.c.put(paramString1, paramString2);
        return this;
    }

    public HttpClient setCookies(String paramString) {
        return addHeader("Cookie", paramString);
    }

    public HttpClient setMessage(String paramString) {
        this.g = paramString;
        return this;
    }


    public HttpClient sendRequest() throws IOException {
        HttpsURLConnection httpsURLConnection = null;

        try {
            httpsURLConnection = (HttpsURLConnection) this.b.openConnection();

            if (this.mSSLSocketFactory != null) {
                httpsURLConnection.setSSLSocketFactory(this.mSSLSocketFactory);
            }

            httpsURLConnection.setDoInput(true);
            httpsURLConnection.setConnectTimeout(3000);
            httpsURLConnection.setReadTimeout(3000);
            httpsURLConnection.setRequestMethod(this.f.name());
            httpsURLConnection.setInstanceFollowRedirects(this.j);
            if (mHostnameVerifier != null) {
                httpsURLConnection.setHostnameVerifier(mHostnameVerifier);
            }

            if (mSslContext != null) {
                httpsURLConnection.setSSLSocketFactory(mSslContext.getSocketFactory());
            }

            if (this.c != null) {
                for (String str : this.c.keySet()) {
                    httpsURLConnection.setRequestProperty(str, this.c.get(str));
                }
            }

            HttpsURLConnection httpsURLConnection1 = httpsURLConnection;
            HttpClient httpClient = this;
            Log.d(a, "The request headers: " + httpsURLConnection1.getRequestMethod() + " " + httpsURLConnection1.getURL() + " " + httpsURLConnection1.getRequestProperties());
            if (httpClient.g != null) Log.d(a, "The request message: " + httpClient.g);

            if (this.g != null && this.g.length() > 0 && this.f != HttpMethod.GET) {
                httpsURLConnection.setDoOutput(true);
                DataOutputStream dataOutputStream;
                (dataOutputStream = new DataOutputStream(httpsURLConnection.getOutputStream())).writeBytes(this.g);
                dataOutputStream.flush();
                dataOutputStream.close();
            }

            this.i = httpsURLConnection.getResponseCode();
            this.d = httpsURLConnection.getHeaderFields();
            if (this.i == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream(), Charsets.utf8Charset));


                StringBuffer stringBuffer = new StringBuffer();
                String str;
                while ((str = bufferedReader.readLine()) != null) {
                    stringBuffer.append(str);
                }
                bufferedReader.close();
                this.h = stringBuffer.toString();
            } else {
                this.h = "";
                Log.e(a, "HTTPs request failed with error code: " + this.i);
            }

            httpsURLConnection1 = httpsURLConnection;
            httpClient = this;
            Log.d(a, "The response headers: " + httpsURLConnection1.getHeaderFields());
            if (httpClient.h != null) Log.d(a, "The response message: " + httpClient.h);
        } catch (IOException iOException) {
            iOException.printStackTrace();
            throw null;
        } finally {
            if (httpsURLConnection != null) {
                httpsURLConnection.disconnect();
            }
        }
        return this;
    }

    public int getStatusCode() {
        return this.i;
    }

    public String getHeader(String paramString, int paramInt) {
        String str = null;
        List<String> list;
        if (this.d != null && (

                list = this.d.get(paramString)) != null && list.size() > paramInt) {
            str = list.get(paramInt);
        }
        return str;
    }

    public List<String> getHeader(String paramString) {
        List<String> list = null;
        if (this.d != null) {
            list = this.d.get(paramString);
        }
        return list;
    }

    public String getResponse() {
        return this.h;
    }


    public HttpClient setFollowRedirects(boolean paramBoolean) {
        this.j = paramBoolean;
        return this;
    }

    public static class MyX509TrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
            Log.e(a, "Certificate:" + chain[0] + "  AuthType:" + authType);
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    public void setMyX509TrustManager() {
        try {
            mSslContext = SSLContext.getInstance("TLS");
            X509TrustManager[] xtmArray = new X509TrustManager[]{new MyX509TrustManager()};
            mSslContext.init(null, xtmArray, new java.security.SecureRandom());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class MyHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            Log.e(a, "Warning:" + hostname + "  vs." + session.getPeerHost());
            return true;
        }
    }

    public void setMyHostnameVerifier() {
        mHostnameVerifier = new MyHostnameVerifier();
    }
}